# 支出跟踪器应用程序

# 添加支出函数
# 参数:
#   expenses: 存储支出记录的列表
#   amount: 支出金额
#   category: 支出类别
def add_expense(expenses, amount, category):
    # 创建支出字典并添加到列表中
    expenses.append({'amount': amount, 'category': category})


# 打印所有支出函数
# 参数:
#   expenses: 存储支出记录的列表
def print_expenses(expenses):
    # 遍历支出列表并打印每条记录
    for expense in expenses:
        print(f'Amount: {expense["amount"]}, Category: {expense["category"]}')


# 计算总支出函数
# 参数:
#   expenses: 存储支出记录的列表
# 返回:
#   所有支出的总和
def total_expenses(expenses):
    # 使用map和lambda函数提取所有支出金额并求和
    return sum(map(lambda expense: expense['amount'], expenses))


# 按类别筛选支出函数
# 参数:
#   expenses: 存储支出记录的列表
#   category: 要筛选的类别
# 返回:
#   属于指定类别的所有支出记录
def filter_expenses_by_category(expenses, category):
    # 使用filter和lambda函数筛选出指定类别的支出
    return filter(lambda expense: expense['category'] == category, expenses)


# 主函数: 程序入口点
def main():
    # 初始化支出列表
    expenses = []
    # 无限循环，直到用户选择退出
    while True:
        # 打印菜单
        print('Expense Tracker')
        print('1. Add an expense')
        print('2. List all expenses')
        print('3. Show total expenses')
        print('4. Filter expenses by category')
        print('5. Exit')

        # 获取用户选择
        choice = input('Enter your choice: ')

        # 根据用户选择执行相应操作
        if choice == '1':
            # 添加支出
            amount = float(input('Enter amount: '))
            category = input('Enter category: ')
            add_expense(expenses, amount, category)

        elif choice == '2':
            # 列出所有支出
            print('All Expenses:')
            print_expenses(expenses)

        elif choice == '3':
            # 显示总支出
            print('Total Expenses: ', total_expenses(expenses))

        elif choice == '4':
            # 按类别筛选支出
            category = input('Enter category to filter: ')
            print(f'Expenses for {category}:')
            expenses_from_category = filter_expenses_by_category(
                expenses, category)
            print_expenses(expenses_from_category)

        elif choice == '5':
            # 退出程序
            print('Exiting the program.')
            break


# 调用主函数启动程序
if __name__ == '__main__':
    main()
